<template>
  <el-tree
    ref="treeRef"
    node-key="id"
    :data="props.data?props.data:tree"
    :props="defaultProps"
    :show-checkbox="showCheckbox"
    :expand-on-click-node="false"
    highlight-current
    default-expand-all/>
</template>
<script lang="ts" setup>
/*
*权限下拉树形菜单
*/
import TreeSelect from '@/components/TreeSelect.vue';
import {
  getCurrentInstance, ref, toRefs, onMounted, defineProps, computed, withDefaults, inject, unref, defineExpose,
} from 'vue';
import { TableData } from '@/types/interface/base_interface';
import { ElTree } from 'element-plus';

const { proxy } = getCurrentInstance(); // 使用proxy代替ctx，因为ctx只在开发环境有效
// 加载部门属性菜单
interface Tree { // 树形接口类型
  id:number;
  name: string;
  children?: Tree[];
}
// 获取父组件传递过来的值，主要用于部门模块
// const table = inject<TableData>('table'); // 表格信息
// 获取父组件传递过来的值
interface Props {
  data?: Tree[],
  disabled?:boolean, // 可用性
  showCheckbox?:boolean, // 是否显示复选框
}
const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  showCheckbox: false,
});
const defaultProps = { // 部门树形菜单显示标签对应的属性名
  value: 'id',
  label: 'name',
  children: 'children',
};

// 从服务端获取树形菜单数据
const tree = ref<Tree[]>();// 定义树形菜单
const getTree = async () => { // 读取树形菜单
  const resData:any = await new proxy.$Request(proxy.$urls.API_URL_BACKSTAGE_PERMISSION_TREE).get();
  if (resData.success) {
    tree.value = resData.data;
  }
};
// 如果没有树形列表的数据传入，则从服务端获取
if (typeof props.data === 'undefined') { // 如果没有值传进来
  onMounted(getTree);
}
// 暴露树形插件的方法
const treeRef = ref<InstanceType<typeof ElTree>>();
const getCheckedNodes = (leafOnly:boolean, includeHalfChecked:boolean) => treeRef.value!.getCheckedNodes(leafOnly, includeHalfChecked);
// 获取树形插件中已经选择的节点
const getCheckedKeys = (leafOnly:boolean) => treeRef.value!.getCheckedKeys(leafOnly);
// 获取树形插件中半选中节点(即子节点选中，但父节点未选中)
const getHalfCheckedKeys = () => treeRef.value!.getHalfCheckedKeys();
// 设置树形菜单初始值
const setCheckedKeys = (keys:number[], leafOnly?:boolean) => treeRef.value!.setCheckedKeys(keys, leafOnly);
const setChecked = (keys:number[]) => treeRef.value!.setChecked(keys, true, false);
defineExpose({ // 参考vue3官方文档，需要将函数暴露出去才能被父组件调用，setup模式是不暴露的
  getCheckedKeys,
  getHalfCheckedKeys,
  getCheckedNodes,
  setCheckedKeys,
  setChecked,
});
</script>
<style lang="scss" scoped>
</style>
